package com.turing.post.report.impl;

import java.math.BigInteger;
import java.util.Date;

import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.turing.post.report.util.VoucherStockDaySettlement;
import com.turing.post.report.util.VoucherStockDaySettlementDao;
import com.turing.post.util.GeneralDao;
import com.turing.post.util.PCPSApplicationException;

@Stateless(mappedName = "report.impl.VoucherStockDaySettlementDaoImpl")
@Remote
@Local
public class VoucherStockDaySettlementDaoImpl implements
		VoucherStockDaySettlementDao {
	/**
	 * 实体管理器
	 * 
	 * @see javax.persistence.EntityManager
	 */
	@PersistenceContext
	protected EntityManager _em;

	public Date getMaxTranDate(String branchNo, Date tranDate,
			BigInteger voucherId) {
		Query query = _em
				.createNativeQuery("select Max(t.tranDate) from VoucherStockDaySettlement t "
						+ "where t.branchNo = ?1 and t.tranDate < ?2 and t.voucherId = ?3");
		query.setParameter(1, branchNo);
		query.setParameter(2, tranDate);
		query.setParameter(3, voucherId);
		return (Date) query.getSingleResult();
	}

	public VoucherStockDaySettlement getVoucherStockDaySettlementByKey(
			VoucherStockDaySettlement vsds) {
		return _em.find(VoucherStockDaySettlement.class, vsds);
	}

	public void insert(VoucherStockDaySettlement vsds)
			throws PCPSApplicationException {
		GeneralDao.insert(_em, vsds);
	}

	@TransactionAttribute(javax.ejb.TransactionAttributeType.REQUIRES_NEW)
	public void removeAllVoucherStockDaySettlementByTranDate(String branchNo,
			Date tranDate) {
		Query query = _em
				.createNativeQuery("delete from VoucherStockDaySettlement t "
						+ "where t.branchNo = ?1 and t.tranDate = ?2");
		query.setParameter(1, branchNo);
		query.setParameter(2, tranDate);
		query.executeUpdate();
	}
}